var express = require('express');
var app = express();
const expressWs = require('express-ws')(app)
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
require('express-async-errors');
var cors = require('cors')

var apiRouter = require('./routes/api');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
// 引入express-ws的WebSocket功能，并混入app，相当于为 app实例添加 .ws 方法


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(cors())
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api', apiRouter);
app.use(function (err, req, res, next) {
    if (err.name == 'UnauthorizedError') {
        if (/^\/api\/getuserinfo/.test(req.url)) {
            res.json({
                flag: false,
                msg: 'token失效'
            })
        } else {
            res.status(401).send('invalid token...');
        }
    } else {
        next(err);
    }
})
app.listen(10000, (req, res) => { // 在10000端口上启动后端服务
    console.log('后端服务端口地址为:  http://localhost:10000');
})
module.exports = app;